package com.myebills.ebpsfrontend.cust.maxis;

import com.myebills.ebpsfrontend.cust.controller.*;
import com.myebills.ebpsfrontend.cust.utils.*;
import com.checkfree.isolutions.customer.persist.*;
import com.checkfree.isolutions.admin.ObjectId;
import com.checkfree.isolutions.statement.persist.Statement;
import com.checkfree.isolutions.utility.CFiError;

import java.util.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ibm.logging.ILogger;
import com.ibm.logging.IRecordType;

/**
 * Module Name  : CusBillDeliveryOptionsServlet_v1r00
 * Description  : Bill Delivery Options for customer
 * Last Updated : 2002-10-10
 *
 * @author Meau
 *
 * Remarks :
 *
 */

public class CusBillDeliveryOptionsServlet_v1r00 extends EbppxTransactionServlet {

    ILogger trcLogger = null;

 // Constant
 	
 	private final SimpleDateFormat ft = new SimpleDateFormat ("dd/MM/yyyy HH:mm:ss");
 	
    public void doTransaction( HttpServletRequest req,HttpServletResponse res)throws ServletException {
		
    	boolean errorRedirected = false;
        final String fName = "doTransaction";
        trcLogger = getTraceLogger(req);
        
        Connection connection = null;

        if (trcLogger.isLogging())
            trcLogger.entry(IRecordType.TYPE_INFO, this, fName);

        try {
            final HttpSession session = req.getSession(false);

            if (null == session)
            throw new IllegalStateException("no session established");

            //Get attribute from session for the logon user
            final EbppxEcsUser ecsUser = (EbppxEcsUser) session.getAttribute(EbppxConstants.ECS_USER);

            EbppxUrlManager urlManager = getUrlManager(req);
            // get the account no selected in JSP
            String strRegisterDate=null;
            String strLastModifyDate=null;
            String status="";
            Date dateRegisterDate =null;
            String strAccNo = ecsUser.getSAccount();
			System.out.println("cus servlet ------ account = "+ecsUser.getSAccount());

            //get the vector of Accounts
            final Vector cfiAccounts = ecsUser.getAccounts();
            final Vector cfiAcctExtKeys = ecsUser.getAccountExternalKeys();


            final Vector cfiOldAccounts = ecsUser.getOldAccounts();
            req.setAttribute("oldAccounts",cfiOldAccounts);

			//to get old acc no for selected new acc no
			String oldAccountNo = ecsUser.getOldAccount(cfiAcctExtKeys, cfiOldAccounts, strAccNo);

			//to check is there any old account number - start
			int oldAccountDisplayCount = 0;
			String oldAccountDisplay = "N";
			for (java.util.Enumeration enumAccounts = cfiAcctExtKeys.elements(); enumAccounts.hasMoreElements();) {
				final String tAccountNo = (String) enumAccounts.nextElement();

				/*if (!AcctDetails.getAcctKey(tAccountNo).equals("")) {
					oldAccountDisplayCount++;
				}*/

			}
			/*if (oldAccountDisplayCount > 0) {
				oldAccountDisplay = "Y";
			}*/
            req.setAttribute("oldAccountDisplay",oldAccountDisplay);
			//to check is there any old account number - end

            req.setAttribute(EbppxConstants.CFI_ACCOUNTS, cfiAccounts);
            req.setAttribute("acctExtKeys",cfiAcctExtKeys);

            String strPhysicalBillSubscription = "";
           // String strCategoryDatabase = EbppxCusDBUtil.getCategoryDatabase();
            
            connection = EbppxCusDBUtil.getDbConnection();
            connection.setAutoCommit(false);
            String cusDatabase = "";
            String emailStatus = "";
            Date currentDate = new Date();

            //if an account has been selected then get the statements
            if (strAccNo !=null && !strAccNo.equals("")) {
                if (trcLogger.isLogging())
                    trcLogger.text(IRecordType.TYPE_INFO, this, fName,"requested acc no: "+strAccNo);

                Merchant cfiMerchant = MerchantHomeImpl.singleton().findByName(ecsUser.getMerchantName());
                Account account = AccountHomeImpl.singleton().findByExternalKeyAndMerchant(strAccNo, cfiMerchant);
                Vector cfiStatements =  StatementUtil.getStatements(account,EbppxCusConstants.STMT_START_MONTH);
                System.out.println("cfiStatements:"+cfiStatements.size());
              
                final EbppxBillDeliveryDataBean dataBean = new EbppxBillDeliveryDataBean();
                final AcctDetails acctDetails = new AcctDetails();

                EbppxAcctDetailsDataBean acctDataBean = new EbppxAcctDetailsDataBean();
               

                System.out.println("currentDate:" + currentDate);

    			//Date dateRegisterDate = AcctDetails.getRegisterDate(connection, strAccNo);

    		    //System.out.println("dateRegisterDate :"+dateRegisterDate);
    			Date dateExpiryDate = null;
                
    			acctDataBean = EbppxCusDBUtil.getLatestEmailDeliveryStatus(connection, strAccNo);
    			
    		
    			
    		    
    			
    			emailStatus = acctDataBean.getEmailStatus();
    			
    		
    			if((emailStatus.equals("Update")) ||(emailStatus.equals("Subscription"))){
    				
    			    dateRegisterDate = acctDataBean.getRegisterDate();
    				if (dateRegisterDate != null) {
        				
        				
        				dateExpiryDate = dateRegisterDate;

        				Calendar c = Calendar.getInstance();
        				c.setTime(dateExpiryDate);
        				c.add(Calendar.DATE, 5);
        				dateExpiryDate = c.getTime();
        				
        				if (currentDate.after(dateExpiryDate)) {
            				
        					 acctDataBean =AcctDetails.getAcctDetails(strAccNo);
            				
            			 
        				
    				     }else{
        				     status = "true";
    				    	 acctDataBean.setEmailSubscription("P");
    				    	 acctDataBean.setSMSNo(acctDetails.getSMSNo(connection, strAccNo));
    				    	 acctDataBean.setSMSSubscription(acctDetails.getSMSSubscription(connection, strAccNo));
    				
    				     }
    				}
    					
    			}else{
    				
    				acctDataBean =AcctDetails.getAcctDetails(strAccNo);
    				
    				
    			}
    	
    			
    		

    			
    		
    			
    		
                if (account!=null){
                
					
					if(acctDataBean.getEmailAdd()==null || acctDataBean.getEmailAdd().equals("")){
						acctDataBean.setEmailAdd(ecsUser.getEmail());
					}
					
				}else{
					errorRedirected = true;
					session.setAttribute("errorMessage","Account not found.");
					redirectToMappedUrl(
					req,
					res,
					"urlLogonFailure",
					"");
				}
                
                connection.commit();
                connection.setAutoCommit(true);
                System.out.println("EBILL REGISTER :"+status);
             
         
                session.setAttribute(EbppxConstants.EBILL_REGISTER_FLAG2, status);
	            req.setAttribute(EbppxConstants.ACCT_DETAILS, acctDataBean);
				req.setAttribute(EbppxConstants.SELFCARE_ACKNOWLEDGEMENT, "");
                req.setAttribute(EbppxConstants.CFI_STATEMENTS, cfiStatements);
                req.setAttribute("accObj", account);
                req.setAttribute("accNo", strAccNo);
            }

            session.setAttribute("fromPage","5");
			if(!errorRedirected){
				forwardToMappedUrl(req, res, EbppxConstants.URL_JSP_PARAM);
			}
        
            }catch (Throwable t) {
            throw new ServletException(t.toString(), t);
        }
        finally {
        	 try {
         		  connection.rollback();
                
                 if (connection!=null){
                   EbppxCusDBUtil.freeDbConnection(connection);
                 }
               /* if (connection1!=null){
                   EbppxCusDBUtil.freeKenanDbConnection(connection1);
                 }*/
               }catch (SQLException e1) {
         			
                 throw new ServletException(e1);
               }catch (Throwable t1){
         			
                 throw new ServletException(t1.toString(), t1);
               }
        }
        
    }
}




